﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Web.UI;

namespace Doo.Controls
{
    [DefaultProperty("Body")]
    [ParseChildren(true, "Body")]
    public class Function : Doo.Scripts.Fields.Field
    {
        /// <summary>
        /// 设置函数的参数
        /// </summary>
        public string Params { get; set; }

        /// <summary>
        /// 是否不加引号，永远为是
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool NoQuote
        {
            get
            {
                return true;
            }
        }

        public override void RenderValue(System.IO.TextWriter writer, Control parent)
        {
            writer.Write(string.Format("function ({0}){{{1}}}", this.Params, this.Body));
        }

        public void RenderMinifyValue(System.IO.TextWriter writer, Control parent, Microsoft.Ajax.Utilities.Minifier minifier)
        {
            //异常：function()转换后会多出一个(,function((
            string result = "function(" + minifier.MinifyJavaScript(string.Format("function ({0}){{{1}}}", this.Params, this.Body)).Substring(11);
            writer.Write(result);
        }

        /// <summary>
        /// 函数体
        /// </summary>
        [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
        public string Body { get; set; }

        public string GetClientReference()
        {
            if (ScriptObject == null) return Name;
            else return string.Format("{0}.{1}", ScriptObject.ClientID, Name);
        }

        /// <summary>
        /// 客户端执行
        /// </summary>
        /// <param name="paras">参数</param>
        public void ClientExec(object[] paras)
        {
            StringBuilder sb = new StringBuilder();
            var page = ScriptObject.Page;
            var server = page.Server;
            sb.AppendFormat("Sys.Application.add_init(function(){{(", GetClientReference());
            foreach (var p in paras)
            {
                if (p is int)
                {
                    sb.Append(p);
                }
                else if (p is bool)
                {
                    sb.Append((bool)p ? "true" : "false");
                }
                else
                {
                    sb.Append('"');
                    sb.Append(p.ToString().Replace("\"", "\\\""));
                    sb.Append('"');
                }
                sb.Append(',');
            }
            sb[sb.Length - 1] = ')';
            sb.Append(";});");
            ScriptManager.RegisterStartupScript(page, page.GetType(), Name, sb.ToString(), true);
        }
    }
}
